﻿using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Sunny.Service;
using Sunny.Util.Attributes;

namespace Sunny.Api.Filters
{
    public class AuthorizationFilter:IAuthorizationFilter
    {
        private readonly PermissionService _permissionService;
        public AuthorizationFilter(PermissionService permissionService)
        {
            _permissionService = permissionService;
        }

        public void OnAuthorization(AuthorizationFilterContext context)
        {
            var attribute = context.ActionDescriptor.EndpointMetadata.FirstOrDefault(t => t.ToString() == typeof(HasPermissionAttribute).FullName);
            if (attribute is HasPermissionAttribute hasPermissionAttribute)
            {
                var code = hasPermissionAttribute.Code;

                if(!_permissionService.HasPermission(code))
                {
                    context.Result =  new JsonResult(Result.Error(CodeMessage.HasNoPermission));
                }
            }
            
        }
    }
}